<template>
  <div class="user-management">
    <el-button text @click="showDialog = !showDialog">用户管理</el-button>
    <article class="manage-box">
      <!-- 第一个弹窗,用于用户管理 -->
      <el-dialog
        v-model="showDialog"
        title="公告信息"
        width="700"
        draggable
        :modal="false"
        class="first-dialog"
      >
        <template #header>
          <div class="my-header">
            <h2>用户管理</h2>
          </div>
        </template>
        <section class="manage-content">
          <nav class="operation-bar">
            <div class="left">
              <el-button :icon="Plus" @click="handleAdd">新增</el-button>
            </div>
            <div class="right">
              <el-input v-model.trim="keywords" placeholder="搜索用户" />
              <el-button :icon="Refresh" @click="keywords = ''"></el-button>
              <el-button @click="handleExport(tableData, '用户名单')">
                <i class="iconfont icon-export"></i>
              </el-button>
            </div>
          </nav>
          <el-table :data="PageTableData" height="240" empty-text="暂无数据" border>
            <el-table-column property="order" label="序号" align="center" width="80" />
            <el-table-column property="userName" label="用户名" align="center" />
            <el-table-column property="userType" label="用户类型" align="center" />
            <el-table-column property="loginStatus" label="登录状态" align="center" width="100" />
            <el-table-column label="操作" align="center" width="200">
              <template #default="{ row }">
                <div class="operation-btn">
                  <el-button
                    type="primary"
                    @click="handleModify(row)"
                    size="small"
                    v-if="row.userName !== nowLoginUser"
                  >
                    修改
                  </el-button>
                  <el-button
                    type="danger"
                    @click="handleDelete(row)"
                    size="small"
                    v-if="row.userName !== nowLoginUser"
                  >
                    注销
                  </el-button>
                  <el-button
                    type="warning"
                    @click="handleOffline(row)"
                    size="small"
                    v-if="row.loginStatus === '在线' && row.userName !== nowLoginUser"
                  >
                    下线
                  </el-button>
                </div>
              </template>
            </el-table-column>
          </el-table>
        </section>
        <template #footer>
          <!-- total设置成关键词过滤后的数据长度 -->
          <el-pagination
            layout="prev, pager, next"
            :total="filterData.length"
            v-model:current-page="tablePage"
            v-model:page-size="pageSize"
          />
        </template>
      </el-dialog>
      <!-- 第二个弹窗,用于新增/修改用户 -->
      <SubMenu
        v-model:showSecondDialog="showSecondDialog"
        v-model:formData="formData"
        v-bind="{ formRules, selectedId, operationType }"
        @operation-success="handleSuccess"
      />
    </article>
  </div>
</template>

<script setup>
import { ref, computed, watch } from 'vue'
import { Refresh } from '@element-plus/icons-vue'
import { handleExport } from '@/utils/toolsFn'
import { useRoute } from 'vue-router'
import { Plus } from '@element-plus/icons-vue'
import { getAllUsers, deleteUser, offlineUser } from '@/api/admin'
import SubMenu from './SubMenu.vue'

const route = useRoute()
const { userName: nowLoginUser } = route.params

const showDialog = ref(false)
const tablePage = ref(1)
const pageSize = ref(8)
const usersData = ref([])
const keywords = ref('')
const showSecondDialog = ref(false)
const formData = ref({})
const formRules = ref({
  userName: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 1, max: 100, message: '用户名长度在1到100个字符', trigger: 'blur' },
  ],
  loginPwd: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 1, max: 100, message: '密码长度在1到100个字符', trigger: 'blur' },
  ],
})
const operationType = ref(0) // 0新增 1修改
const selectedId = ref(-1)

// 添加索引
const tableData = computed(() => {
  return usersData.value.map((item, index) => {
    const { loginStatus, ...rest } = item
    if (item.userName === nowLoginUser) {
      return { ...rest, order: index + 1, loginStatus: '正在登录' }
    } else {
      return { ...rest, order: index + 1, loginStatus: loginStatus ? '在线' : '离线' }
    }
  })
})

// 关键词过滤
const filterData = computed(() => {
  if (!keywords.value) return tableData.value
  else
    return tableData.value.filter(
      (item) => item?.userName.includes(keywords.value), //使用可选链运算符
    )
})
// 分页数据
const PageTableData = computed(() => {
  const start = (tablePage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return filterData.value.slice(start, end) //适用关键词过滤后的数据切片
})

const handleAdd = () => {
  operationType.value = 0
  showSecondDialog.value = true
}
const handleModify = async ({ id, userName, loginPwd }) => {
  operationType.value = 1
  showSecondDialog.value = true
  formData.value = { userName, loginPwd }
  selectedId.value = id
}
const handleDelete = async (row) => {
  const id = row.id
  if (!id) return
  try {
    await deleteUser(id)
    ;({ data: usersData.value } = await getAllUsers())
  } catch {}
}
const handleOffline = async (row) => {
  const id = row.id
  if (!id) return
  try {
    await offlineUser(id)
    ;({ data: usersData.value } = await getAllUsers())
  } catch {}
}
const handleSuccess = async (status) => {
  selectedId.value = -1
  if (status) {
    ;({ data: usersData.value } = await getAllUsers())
  }
}

watch(showDialog, async (val) => {
  if (val) {
    ;({ data: usersData.value } = await getAllUsers())
  } else {
    usersData.value = []
  }
})
</script>

<style lang="scss" scoped>
.manage-box {
  :deep(.first-dialog) {
    .my-header {
      font-size: 1.5rem;
      color: #666;
      font-weight: 600;
    }
    .el-dialog__body {
      border-top: 1px solid #eee;
      .manage-content {
        .content-title {
          background-color: #eee;
          padding: 10px;
          color: #999;
          font-size: 1.1rem;
        }
        .operation-bar {
          display: flex;
          justify-content: end;
          padding: 10px 0;
          .left {
            flex: 4 4;
            display: flex;
          }
          .right {
            flex: 6 6;
            display: flex;
            .el-input {
              flex-basis: 1;
              margin-right: 12px;
            }
            .el-button {
              flex: 0 0 auto;
            }
          }
        }
        .operation-btn {
          display: flex;
          justify-content: center;
        }
        .el-table {
          .el-table__header {
            tr {
              .el-table__cell {
                background-color: #eee;
              }
            }
          }
        }
      }
    }

    .el-pagination {
      justify-content: center;
    }
  }
}
</style>
